<!-- 填写表单 -->
<template>
  <div class="fill-in-form-wp">
  	<div class="h-full" style="overflow:auto;">
  		<el-card class="mb-10" shadow="hover">
	  		<el-descriptions :column="3" border>
	  			<el-descriptions-item :span="3" label="项目名称">{{_d.projectDetail.projectName || ''}}</el-descriptions-item>
			    <el-descriptions-item label="编号">{{_d.projectDetail.projectCode || ''}}</el-descriptions-item>
			    <el-descriptions-item label="类别">{{_d.projectDetail.categoryName || ''}}</el-descriptions-item>
			    <el-descriptions-item label="采购方式">{{_d.projectDetail.procurementMethod || ''}}</el-descriptions-item>
			    <el-descriptions-item label="项目金额">{{_d.projectDetail.budget || ''}}元</el-descriptions-item>
			    <el-descriptions-item label="负责人">{{oUserInfo.$state.userInfos.account || ''}}</el-descriptions-item>
			    <el-descriptions-item label="联系方式">{{oUserInfo.$state.userInfos.phone || ''}}</el-descriptions-item>
			    <el-descriptions-item :span="3" label="项目描述">{{_d.projectDetail.description || ''}}</el-descriptions-item>
			  </el-descriptions>
	  	</el-card>

	  	<el-card shadow="hover" style="overflow: visible;">
	  		<template #header>
	  			<div class="flex justify-between items-center">
	  				<div class="flex items-center">
							<el-radio-group size="default" v-model="_d.processId" @change="getFormList(_d.processId)">
					      <el-radio-button class="process-btn" v-for="(item, index) in _d.processList" :key="item.id" :label="item.id" :disabled="getProcessDisabled(index)">
					      	<div class="flex items-center">
					      		<el-icon v-if="item.status == 1" class="mr-5" color="#67C23A" size="20"><SuccessFilled /></el-icon>
					      		<div v-else class="circle1 mr-5"></div>
					      		<b>{{item.phaseName}}</b>
					      	</div>
					      </el-radio-button>
					    </el-radio-group>
	  				</div>
	  				<el-button v-if="canEdit" size="default" type="primary" @click="setPhaseOk()">提交阶段材料</el-button>
	  			</div>
	  		</template>
	  		<el-radio-group class="mb-15" size="small" v-model="_d.formId" @change="getFormContent(_d.formId)">
		      <el-radio-button class="form-btn" v-for="(item, index) in _d.formList" :key="index" :label="item.id">
		      	<div class="flex items-center">
		      		<el-icon v-if="item.status == 1" class="mr-5" size="14" color="#67C23A"><SuccessFilled /></el-icon>
		      		<el-icon v-else-if="item.checkResult == 1" size="14" class="mr-5 check-icon" color="#027BFD"><checkIcon></checkIcon></el-icon>
		      		<div v-else class="circle1 mr-5"></div>
		      		<span>{{item.formName}}</span>
		      	</div>
		      </el-radio-button>
		    </el-radio-group>

		    <template v-if="oForm">
		    	<el-card class="mb-15 preview-card">
			    	<template #header>
			    		<div class="flex justify-between items-center">
			    			<!-- {{oForm.formName}} -->
			    			<div class="title"></div>
			    			<div>
			    				<el-button size="small" @click="exportContent()">导出</el-button>
			    				<el-button size="small" @click="printContent()">打印</el-button>
			    				<template v-if="canEdit">
			    					<template v-if="!oForm.check && oForm.status == 0">
			    						<el-button v-auth="'form:save'" size="small" @click="saveContent()">暂存</el-button>
			    						<el-button v-auth="'form:save'" type="primary" size="small" @click="setFormOk()">完成表单</el-button>
			    					</template>
			    					<template v-if="oForm.check && oForm.checkResult == 0">
			    						<el-button v-auth="'form:save'" size="small" @click="saveContent()">暂存</el-button>
			    						<el-button v-auth="'form:save'" type="primary" size="small" @click="setFormCheck()">提交审核</el-button>
			    					</template>
			    				</template>
			    			</div>
			    		</div>
			    	</template>
			    	<div v-if="_d.formData.instruction" class="fillin-instruction">
			    		<div class="label">填写说明：</div>
			    		<div class="value">{{_d.formData.instruction}}</div>
			    	</div>
			    	<pdfPreview v-if="_d.formData.content" ref="previewRef" :is-init="_d.formData.status != 1" :config="_d.formData.content"></pdfPreview>
			    </el-card>
			    <el-row :gutter="15">
			    	<el-col :span="12">
			    		<div class="file-box">
						    <el-card class="mb-15">
						    	<template #header>
					    		<div class="flex justify-between items-center">
					    			<div class="title">文件清单</div>
					    			<div>
					    				<el-button v-if="canEdit" size="small" @click="uploadFile()">上传</el-button>
					    			</div>
					    		</div>
					    	</template>
					    		<el-table :data="_d.fileList" style="width: 100%" border height="200px">
										<el-table-column type="index" label="序号" width="55" align="center" />
										<el-table-column prop="oldName" label="文件名称" show-overflow-tooltip />
										<!-- <el-table-column prop="state" label="提交结果" width="200" show-overflow-tooltip /> -->
										<el-table-column label="操作" width="150" align="center" fixed="right" show-overflow-tooltip>
											<template #default="scope">
												<SeeFile :name="scope.row.oldName" :url="scope.row.url"/>
												<el-button icon="el-icon-delete" size="small" text type="primary" @click="deleteFile(scope.row)">删除</el-button>
											</template>
										</el-table-column>
									</el-table>
						    </el-card>
					    </div>
			    	</el-col>
			    	<el-col :span="12">
			    		<div class="file-box">
						    <el-card class="mb-15">
						    	<template #header>
					    		<div class="flex justify-between items-center">
					    			<div class="title">关联文件</div>
					    		</div>
					    	</template>
					    		<el-table :data="_d.relationList" style="width: 100%" border height="200px">
										<el-table-column type="index" label="序号" width="55" align="center" />
										<el-table-column prop="showName" label="文件名称" show-overflow-tooltip />
										<el-table-column label="操作" width="150" align="center" fixed="right" show-overflow-tooltip>
											<template #default="scope">
												<SeeFile :name="scope.row.showName" :url="scope.row.url"/>
											</template>
										</el-table-column>
									</el-table>
						    </el-card>
					    </div>
			    	</el-col>
			    </el-row>
		    </template>
	  	</el-card>
  	</div>

  	<input v-show="false" ref="fileRef" type="file" @change="fileChange">
  </div>
</template>

<script setup>
	import { reactive, ref, computed, onMounted } from 'vue'
	import { ElNotification, ElMessageBox } from 'element-plus';
	import {SuccessFilled, Help} from '@element-plus/icons-vue';
	import checkIcon from "./modules/checkIcon.vue";
	import excelPreview from "/@/views/template/excel/preview/index.vue";
	import pdfPreview from "/@/views/template/pdf/preview/index.vue";
	import {ImportFile} from "/@/utils/Tools.js";
	import {$get, $post, $postFile} from '/@/utils/request';
	import {useUserInfo} from "/@/stores/userInfo.ts";
	import SeeFile from "/@/components/SeeFile/index.vue";

	const oUserInfo = useUserInfo();
	const previewRef = ref();
	const fileRef = ref();

	const _d = reactive({
		projectId: '',
		projectDetail: {},

		// 阶段数据
		processId: '',
		processList: [],


		// 表单数据
		formId: '',
		formList: [],
		formData: {}, // 表单数据

		previewData: null,
		// 文件清单
		fileList: [],

		// 关联文件列表
		relationList: [],
	})

	// 阶段是否可编辑
	const canEdit = computed(() => {
		let obj = _d.processList.find(item => item.id == _d.processId);
		return obj && obj.status == 0 ? true : false;
	})

	// 当前的表单
	const oForm = computed(() => {
		return _d.formList.find(item => item.id == _d.formId);
	})

	onMounted(() => {
		_d.projectId = localStorage.getItem('project_id');

		// 获取项目详情
		getProjectDetail();
		// 查询项目阶段
		getPhase();

		// ImportFile('/FileTemplate/采购预算清单-预算明细.txt').then(res => {
		// 	_d.previewData = res;
		// 	console.log(res);
		// })
	})

	// 获取项目详情
	async function getProjectDetail() {
		var res = await $post('/projectService/getproject', _d.projectId);
		if(res.result) {
			let obj = res.result;
			obj.categoryName = await getCategoryName(obj.projectTemplateId);
			_d.projectDetail = obj;
		}
	}

	// 获取类别名称
	async function getCategoryName(id) {
		let params = {
			input: id
		}
		var res = await $get('/projectTemplateModule/getprojecttemplate', params);
		var list = res.result;
		return list.length ? list[0].projectName : '';
	}

	// 查询项目阶段
	function getPhase() {
		$post('/projectService/getphasebyprojectid', _d.projectId).then(res => {
			_d.processList = res.result;
			// 设置默认阶段
			let obj = _d.processList.find(item => item.status == 0);
			_d.processId = obj ? obj.id : _d.processList[0].id;
			// 查询当前阶段的表单
			getFormList(_d.processId);
		})
	}

	// 查询当前阶段的表单
	function getFormList(id) {
		$get('/projectService/getformsbyphaseid/'+id).then(res => {
			_d.formList = res.result;
			// 设置默认的
			let obj = _d.formList.find(item => item.status == 0);
			_d.formId = obj ? obj.id : _d.formList[0].id;
			// 查询当前表单的内容
			getFormContent(_d.formId);

		})
	}

	// 获取流程是否可以点击
	function getProcessDisabled(index) {
		if(index == 0) {
			return false;
		}
		return _d.processList[index-1].status == 1 ? false : true;
	}

	// 查询当前表单的内容
	function getFormContent(id) {
		// 查询表单内容
		$post('/projectService/geformbyid/'+id).then(res => {
			try {
				res.result.content = JSON.parse(res.result.content);
				_d.formData = res.result;
			} catch(err) {
				console.log('解析content失败');
				_d.formData = {};
			} 
		})
		// 查询当前表单的附件列表
		getFileList(id);
		// 查询表单关联文档列表
		getRelationList(id);
	}

	// 查询当前表单的附件列表
	function getFileList(id) {
		$get('/projectService/getformfiles/'+id).then(res => {
			_d.fileList = res.result.map(item => {
				item.oldName = item.fileName+item.suffix;
				return item;
			});
		})
	}

	// 查询表单关联文档列表
	function getRelationList(id) {
		$get('/projectService/getformtemplatefiles/'+id).then(res => {
			_d.relationList = res.result.map(item => {
				item.showName = item.fileName+item.suffix;
				return item;
			});
		})
	}

	// ------------------------------
	// 保存pdf内容
	function saveContent() {
		ElMessageBox.confirm('此操作将保存该表单，是否继续？', '提示', {
			type: 'warning'
		}).then(async () => {
			let content = await previewRef.value.getCode();
			let params = {
				id: _d.formId,
				content: content
			}
			$post('/projectService/modifyform', params).then(res => {
				if(res.code == 200) {
					ElNotification({
				    title: '提示',
				    message: '保存成功',
				    type: 'success',
				  })
				}
			})
		})
	}

	// 表单-提价审核
	function setFormCheck() {
		if(!_d.fileList.length) {
			ElNotification({
		    title: '提示',
		    message: '清先上传文件清单',
		    type: 'error',
		  })
		  return;
		}
		ElMessageBox.confirm(`此操作将提交审核表单，是否继续？`, '提示', {
			type: 'warning'
		}).then(async () => {
			let params = {
				id: _d.formId,
				checkResult: 1,
				check: oForm.value.check,
				content: await previewRef.value.getCode()
			}
			$post('/projectService/modifyform', params).then(res => {
				if(res.code == 200) {
					ElNotification({
				    title: '提示',
				    message: '提交成功',
				    type: 'success',
				  })
					let obj = _d.formList.find(item => item.id == _d.formId);
					if(obj) {
						obj.checkResult = 1;
					}
				}
			})
		})
	}

	// 表单-完成
	function setFormOk() {
		if(!_d.fileList.length) {
			ElNotification({
		    title: '提示',
		    message: '清先上传文件清单',
		    type: 'error',
		  })
		  return;
		}
		ElMessageBox.confirm(`此操作将完成表单，是否继续？`, '提示', {
			type: 'warning'
		}).then(async () => {
			let params = {
				id: _d.formId,
				status: 1,
				content: await previewRef.value.getCode()
			}
			$post('/projectService/modifyform', params).then(res => {
				if(res.code == 200) {
					ElNotification({
				    title: '提示',
				    message: '提交成功',
				    type: 'success',
				  })
					let obj = _d.formList.find(item => item.id == _d.formId);
					if(obj) {
						obj.status = 1;
					}
				}
			})
		})
	}

	// 导出内容
	function exportContent() {
		previewRef.value.export();
	}

	// 打印
	function printContent() {
		previewRef.value.print();
	}

	// 上传附件
	function uploadFile() {
		fileRef.value.click();
	}
	// 上传附件改变
	function fileChange(e) {
		let files = e.target.files;
		if(!files.length) {
			return;
		}
		let file = files[0];
		let fd = new FormData();
    fd.append("file", file);
    $postFile(`/projectService/uploadformfile?path=${_d.projectId}&id=${_d.formId}&isTemplate=false`, fd).then(res => {
    	if(res.code == 200) {
    		ElNotification({
			    title: '提示',
			    message: '上传成功',
			    type: 'success',
			  })
			  // 更新附件列表
			  getFileList(_d.formId);
    	}
    }).finally(() => {
    	e.target.value = '';
    })
	}

	// 删除
	function deleteFile(row) {
		ElMessageBox.confirm('此操作将删除该文件，是否继续？', '提示', {
			type: 'warning'
		}).then(() => {
			$post('/projectService/removeformfile/'+row.id).then(res => {
				if(res.code == 200) {
					// 查询当前表单的附件列表
					getFileList(_d.formId);
				}
			})
		})
	}

	// 提交阶段
	function setPhaseOk() {
		ElMessageBox.confirm('此操作将提交该阶段材料，是否继续？', '提示', {
			type: 'warning'
		}).then(() => {
			$post('/projectService/setphasestatus/'+_d.processId).then(res => {
				if(res.code == 200) {
					ElNotification({
				    title: '提示',
				    message: '提交成功',
				    type: 'success',
				  })
				  if(res.code == 200) {
						let obj = _d.processList.find(item => item.id == _d.processId);
						if(obj) {
							obj.status = 1;
						}
					}
				}
			})
		})
	}

</script>

<style lang="scss" scoped>
.fill-in-form-wp {
	overflow: auto;
	.process-btn {
		:deep(.el-radio-button__inner) {
			padding: 0 15px;
			height: 32px;
			display: flex;
			align-items: center;
		}
		.circle1 {
			width: 16px;
			height: 16px;
			border: 3px solid #027BFD;
			border-radius: 50%;
		}
		&.is-active .circle1 {
			border-color: #fff;
		}
	}
	.form-btn {
		:deep(.el-radio-button__inner) {
			padding: 0 11px;
			height: 26px;
			display: flex;
			align-items: center;
		}
		.circle1 {
			width: 14px;
			height: 14px;
			border: 3px solid #027BFD;
			border-radius: 50%;
		}
		&.is-active .check-icon {
			color: #fff;
		}
		&.is-active .circle1 {
			border-color: #fff;
		}
	}

	.file-box {
		margin: 0 auto;
		width: 100%;
		max-width: 1000px;
	}
}

.fillin-instruction {
	position: relative;
	padding-left: 5em;
	.label {
		position: absolute;
		top: 0;
		left: 0;
		padding: 0;
	}
	.value {
		width: 100%;
	}
}

</style>
<style lang="scss">
.fill-in-form-wp {
	.preview-card {
		.el-card__header {
			padding: 10px 20px;
		}
	}
}	
</style>

